package com.doge.calcalbum.widgets

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.animation.DecelerateInterpolator
import android.widget.ProgressBar


class HorizontalProgressView @JvmOverloads constructor(
    context: Context,
    attr: AttributeSet? = null,
    defStyleStyle: Int = 0
) : ProgressBar(context, attr, defStyleStyle) {

    private var dirtyAnim: ValueAnimator? = null
    private var isStarted = false

    fun stop() {
        isStarted = false
        dirtyAnim?.cancel()
        internalProcess(progress, 100, 100) {
            visibility = View.GONE
        }
    }

    fun start() {
        if (!isStarted) {
            isStarted = true
            visibility = View.VISIBLE

            internalProcess(0, 30, 200) {
                internalProcess(30, 70, 1000) {
                    internalProcess(70, 90, 5000) {
                        internalProcess(90, 95, Long.MAX_VALUE) {

                        }
                    }
                }
            }
        }
    }

    private fun internalProcess(
        start: Int,
        end: Int,
        d: Long,
        callback: () -> Unit
    ) {
        dirtyAnim?.cancel()
        dirtyAnim = ValueAnimator.ofInt(start, end)
            .apply {
                duration = d
                addListener(object : AnimatorListenerAdapter() {
                    var isCanceled = false

                    override fun onAnimationEnd(animation: Animator?) {
                        if (isCanceled) return
                        progress = end
                        callback()
                    }

                    override fun onAnimationCancel(animation: Animator?) {
                        isCanceled = true
                    }
                })
                addUpdateListener {
                    progress = it.animatedValue as Int
                }
                interpolator = DecelerateInterpolator()
                start()
            }

    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        dirtyAnim?.cancel()
    }
}